import htmlElementUtils from "@/utils/htmlElementUtils.ts";

const CSS = `position:absolute;left:0;top:-100%;width:100%;height:100%;margin:1px 0 0;border:none;opacity:0;pointer-events:none;`;

/**
 * 监听大小变化
 * @param element
 * @param handler 三个参数 element,oldHeight,oldWidth
 * @param immediate 是否立即执行
 * @return {(function(): void)|*}返回移除监听的函数
 */
function simpleElementResizeDetector(element, handler,immediate = false) {
  const frame = document.createElement('iframe');
  const supportsPE = document.documentMode < 11 && 'pointerEvents' in frame.style;

  frame.style.cssText = `${CSS}${supportsPE ? '' : 'visibility:hidden;'}`;
  let oldHeight = htmlElementUtils.getStyle(element, 'height')
  let oldWidth = htmlElementUtils.getStyle(element, 'width')
  let runFunc = () =>{
    let nowHeight = htmlElementUtils.getStyle(element, 'height')
    let nowWidth = htmlElementUtils.getStyle(element, 'width')
    if (nowWidth !== oldWidth || nowHeight !== oldHeight) {
      handler(element, oldHeight, oldWidth, nowHeight, nowWidth);
      oldHeight = nowHeight;
      oldWidth = nowWidth;
    }
  }
  frame.onload = () => {
    frame.contentWindow.onresize = () => {
      runFunc()
    };
  };
  element.appendChild(frame);
  if(immediate) {
    runFunc()
  }
  return () => {
    frame.remove();
  }
}

/**
 * 用法
 *     let removeFunc = simpleElementResizeDetector(this.$refs.sizeListen,this.sizeListenCall)
 * 移除监听
 *    removeFunc()
 */
export default simpleElementResizeDetector

